package com.zjeav.lingjiao.base.baseBean;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.dalimao.corelibrary.swipeback.SwipeBackActivity;
import com.dalimao.corelibrary.view.LoadProgressDialog;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.tools.SystemTools;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.home.RestructureMainActivity;
import com.zjeav.lingjiao.ui.music.MusicService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import static com.zjeav.lingjiao.base.tools.SystemTools.isServiceRunning;


/**
 * Created by zcc on 2016/11/28.
 */

public class BaseActivity extends SwipeBackActivity {
    private LinearLayout mBaseView;
    private View actionBar;
    private static long mPreTime;
    private static Activity mCurrentActivity;// 对所有activity进行管理
    public static List<Activity> mActivities = new LinkedList<Activity>();
    protected Bundle savedInstanceState;
    public PermissionListener mPermissionListener;

    @Override
    public void setContentView(int layoutResID) {
        mBaseView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.status_main_layout, null);//状态栏
        LayoutInflater.from(this).inflate(layoutResID, mBaseView);  //把状态栏添加到主视图
        setContentView(mBaseView);

        this.savedInstanceState = savedInstanceState;
        loadProgressDialog = new LoadProgressDialog(this, com.dalimao.corelibrary.R.style.MyDialog);

        //初始化的时候将其添加到集合中
        synchronized (mActivities) {
            mActivities.add(this);
        }
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initView();//设置状态栏的高度跟样式
    }

    private void initView() {
        //改变statusbar的颜色
        actionBar = mBaseView.findViewById(R.id.action_bar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            actionBar.setVisibility(ViewGroup.VISIBLE);
            Window w = getWindow();
            w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,  //设置StatusBar透明
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int id = 0;
            id = getResources().getIdentifier("status_bar_height", "dimen", //获取状态栏的高度
                    "android");
            if (id > 0) {
                actionBar.getLayoutParams().height = getResources() //设置状态栏的高度
                        .getDimensionPixelOffset(id);
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mCurrentActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCurrentActivity = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //销毁的时候从集合中移除
        synchronized (mActivities) {
            mActivities.remove(this);
        }
    }


    /**
     * 退出应用的方法
     */
    public static void exitApp() {

        ListIterator<Activity> iterator = mActivities.listIterator();
        SharedPreferencesUtils.setParam(mCurrentActivity,"currentTime",0);
        while (iterator.hasNext()) {
            Activity next = iterator.next();
            next.finish();
        }
        if (isServiceRunning(mCurrentActivity, "com.zjeav.lingjiao.ui.music.MusicService")) {
            mCurrentActivity.stopService(new Intent(mCurrentActivity, MusicService.class));
        }
    }

    /**
     * 统一退出控制
     */
    @Override
    public void onBackPressed() {
        if (mCurrentActivity instanceof RestructureMainActivity){
            //如果是主页面
            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
                UIUtils.showToast("再按一次，退出应用");
                mPreTime = System.currentTimeMillis();
                return;
            }

          //  NimMain.logout();
        }
        super.onBackPressed();// finish()
    }

    /**
     * 申请运行时权限
     */
    public void requestRuntimePermission(String[] permissions, PermissionListener permissionListener) {
        mPermissionListener = permissionListener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            permissionListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;
        }
    }
}
